package org.xiezc;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.io.InputStreamReader;
import java.util.Properties;

import javax.servlet.ServletContextEvent;

import org.apache.log4j.Logger;
import org.springframework.web.context.ContextLoaderListener;
import org.xiezc.aes.AesException;
import org.xiezc.aes.WXBizMsgCrypt;
import org.xiezc.entity.WechatConfig;
import org.xiezc.util.BaseUtil;

/**
 * 初始化监听器类，此监听器继承了spring的监听器
 * 
 * @author xiezc
 *
 */
public class InitializeListerner extends ContextLoaderListener {

	private static Logger log = Logger.getLogger(InitializeListerner.class);
	/**
	 * 微信的加密解密，校验等加密操作类
	 */
	public static WXBizMsgCrypt wXBizMsgCrypt = null;
	/**
	 * 微信的配置信息类
	 */
	public static WechatConfig wechatConfig = WechatConfig.getInstance();
	/**
	 * 微信的classpath
	 */
	public static String classPath = new BaseUtil().getRootPath();

	@Override
	public void contextInitialized(ServletContextEvent event) {
		super.contextInitialized(event);
		log.info("Spring初始化完毕。开始加载微信的配置");
		Properties properties = new Properties();
		try {
			InputStreamReader isr = new InputStreamReader(
					new FileInputStream(classPath + "com/wechat/properties/wechat.properties"));
			properties.load(isr);
			//读取配置信息有时候会把配置信息中的空格页读取进去
			wechatConfig.setAppId(properties.getProperty("AppId").trim());
			wechatConfig.setAppSecret(properties.getProperty("AppSecret").trim());
			wechatConfig.setToken(properties.getProperty("Token").trim());
			wechatConfig.setEncodingAESKey(properties.getProperty("EncodingAESKey").trim());
			wechatConfig.setUrl(properties.getProperty("Url").trim());
			wechatConfig.setEncryptType(properties.getProperty("EncryptType").trim());
			// 获得accessToken
			wechatConfig.updateAccessToken();
			log.info("微信配置加载完成");
			wXBizMsgCrypt = new WXBizMsgCrypt(wechatConfig.getToken(), wechatConfig.getEncodingAESKey(),
					wechatConfig.getAppId());
			log.info("加密操作类初始化完成");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (AesException e) {
			e.printStackTrace();
		}

	}

	@Override
	public void contextDestroyed(ServletContextEvent event) {
		super.contextDestroyed(event);
		log.info("服务器关闭");
	}

}
